package com.situ.mall.common.util;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.Objects;

public class StringUtil {
    public static final Long K_SIZE = 1024L;
    public static final Long M_SIZE = K_SIZE * K_SIZE;
    public static final Long G_SIZE = M_SIZE * K_SIZE;
    public static final String B = "B";
    public static final String K = "KB";
    public static final String M = "MB";
    public static final String G = "GB";
    public static Boolean isNotBlank(String str) {
        if(str!=null&&!"".equals(str)) {
            return true;
        }else {
            return false;
        }
    }
    //md5加密算法
    public static String md5(String str) {
        try {
            MessageDigest md=MessageDigest.getInstance("MD5");
            md.update(str.getBytes("UTF-8"));
            return new BigInteger(1,md.digest()).toString(16);
        }catch(NoSuchAlgorithmException|UnsupportedEncodingException ignored) {

        }
        return null;
    }
    //文件大小转kb
    public static String formatFileSize(Long fileSize) {
        String fileSizeStr = "";
        if (Objects.isNull(fileSize)) {
            return fileSizeStr;
        }
        if (fileSize == 0L) {
            return "0".concat(B);
        }
        // 小数位数自定义
        DecimalFormat df = new DecimalFormat("#.##");
        if (fileSize < K_SIZE) {
            fileSizeStr = df.format((double) fileSize) + B;
        } else if (fileSize < M_SIZE) {
            fileSizeStr = df.format((double) fileSize / K_SIZE) + K;
        } else if (fileSize < G_SIZE) {
            fileSizeStr = df.format((double) fileSize / M_SIZE) + M;
        } else {
            fileSizeStr = df.format((double) fileSize / G_SIZE) + G;
        }
        return fileSizeStr;
    }

}